package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrganAddressDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.OrganAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 检查组服务
 */
@Service(interfaceClass = OrganAddressService.class)
@Transactional
public class OrganAddressServiceImpl implements OrganAddressService {

    @Autowired
    private OrganAddressDao organAddressDao;

    @Autowired
    private OrderDao orderDao;

    //添加检查组合，同时需要设置检查组合和检查项的关联关系
    public void add(OrganAddress organAddress) {
        organAddressDao.add(organAddress);
    }

    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<OrganAddress> page = organAddressDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    public OrganAddress findById(Integer id) {
        return organAddressDao.findById(id);
    }

    //编辑检查组，同时需要更新和检查项的关联关系
    public void edit(OrganAddress organAddress) {
        organAddressDao.edit(organAddress);
    }

    /**
     * 查询所有记录
     * @return
     */
    public List<OrganAddress> findAll() {
        return organAddressDao.findAll();
    }

    /**
     * 根据id删除机构地址
     * @param id
     */
    public void deleteById(String id) {
        // 关联预约表，如果该机构有预约，则不能删除
        //查询当前检查项是否和检查组关联
        long count = orderDao.findCountByOrganId(id);
        if(count > 0){
            //当前检查项被引用，不能删除
            throw new RuntimeException("当前机构下有预约，不能删除");
        }
        organAddressDao.deleteById(Integer.parseInt(id));
    }

    @Override
    public List<OrganAddress> findOrgans(String lng, String lat) {
        Map<String,String> map = new HashMap<>();
        map.put("lng", lng);
        map.put("lat", lat);
        return organAddressDao.findOrgans(map);
    }
}
